Reverse Nodes in k-Group

Given a linked list, reverse the nodes of a linked list k at a time and return its modified list.

If the number of nodes is not a multiple of k then left-out nodes in the end should remain as it is.

You may not alter the values in the nodes, only nodes itself may be changed.

Only constant memory is allowed.

For example,

Given this linked list: 1->2->3->4->5

For k = 2, you should return: 2->1->4->3->5

For k = 3, you should return: 3->2->1->4->5

Solution:

  1. /**
  2. * Definition for singly-linked list.
  3. * public class ListNode {
  4. * int val;
  5. * ListNode next;
  6. * ListNode(int x) { val = x; }
  7. * }
  8. */
  9. public class Solution {
  10. public ListNode reverseKGroup(ListNode head, int k) {
  11. if (getLength(head) < k) {
  12. return head;
  13. }
  14. ListNode prev = null;
  15. ListNode curr = head;
  16. int count = k;
  17. while (curr != null && count > 0) {
  18. ListNode next = curr.next;
  19. curr.next = prev;
  20. prev = curr;
  21. curr = next;
  22. count--;
  23. }
  24. // prev is the new head
  25. // head is the new tail
  26. // curr is the next list
  27. head.next = reverseKGroup(curr, k);
  28. return prev;
  29. }
  30. int getLength(ListNode head) {
  31. int len = 0;
  32. while (head != null) {
  33. head = head.next;
  34. len++;
  35. }
  36. return len;
  37. }
  38. }